# @Time : 2024-10-19 14:33
# @Author : Fioman 
# @Phone : 13149920693
"""
lambda: 匿名函数,没有名字的函数,并且没有return语句
格式为: lambda 参数1,参数2,...:表达式
表达式只能是单一的语句,不能是多条语句
"""
# region 1. 简单的lambda表达式
add = lambda a, b: a + b
print(add(3, 4))
# 不带返回值的lambda表达式
pt = lambda a, b: print(a, b)
pt(3, 4)

# endregion

# region  2. 作为内置函数的参数 map() | filter() | sorted() |  reduce()
nums = [1, 2, 3, 4]
squared = list(map(lambda x: x ** 2, nums))
print(squared)

nums = range(1, 11)
evenNums = list(filter(lambda x: x % 2 == 0, nums))
print(evenNums)

students = [("John", 22), ("Alice", 20), ("Bob", 24)]
students.sort(key=lambda x: x[1], reverse=True)  # 按照年龄降序
print(students)

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
from functools import reduce

# reduce的工作原理,先从前两个数进行累加,然后将结果和后面的数据一一累加,直到最后一个数据
product = reduce(lambda x, y: x + y, nums)  # 累积运算
print(product)

# endregion

# region 3. 用于条件表达式
maxNum = lambda x, y: x if x > y else y
print(maxNum(10, 20))
students = [
    {"name": "John", "age": 22, "grade": 90},
    {"name": "Alice", "age": 20, "grade": 95},
    {"name": "Fioman", "age": 20, "grade": 100},
    {"name": "Bob", "age": 24, "grade": 88}
]
# 年龄升序,分数降序进行排列,排序的时候可以返回一个元组,多重条件排序
sortedStu = sorted(students, key=lambda x: (x["age"], -x["grade"]))
print(sortedStu)
# endregion

# region 4. 简化列表或者字典推导
nums = [1, 2, 3, 4]
result = [lambda x=x: x ** 2 for x in nums if x % 2 == 0]
print(result)
print([f() for f in result])


# endregion

# region 5. lambda 在另外一个函数的返回值中
def power(x):
    return lambda n: x ** n


cube = power(2)(3)
print(cube)
res = power(3)(4)  # 3 ** 4
print(res)
# endregion
